<template>
	<a-modal :visible="visible" title="地点查询" @cancel="handleClose" @ok="handleClose" :footer="null" :width="600"
		:destroyOnClose="true">
		<div class="search-container">
			<!-- 搜索输入框 -->
			<a-input-search ref="searchInput" v-model="searchKeyword" placeholder="请输入地点名称" @search="handleSearch"
				@pressEnter="handleSearch" :loading="loading" allow-clear enter-button="查询" />

			<!-- 搜索结果列表 -->
			<div class="results-container">
				<a-list v-if="results && results.length > 0" :data-source="results"
					:locale="{ emptyText: loading ? '加载中...' : '暂无数据' }">
					<a-list-item slot="renderItem" slot-scope="item">
						<a-list-item-meta>
							<a slot="title" @click="selectLocation(item)" class="location-name">{{ item.name }}</a>
							<div slot="description" class="location-address">{{ item.cityname + item.adname +
								item.address }}</div>
						</a-list-item-meta>
					</a-list-item>
				</a-list>

				<!-- 空状态 -->
				<a-empty v-else-if="!loading && results.length === 0" description="暂无搜索结果" />

				<!-- 加载状态提示 -->
				<div v-if="loading" class="loading-container">
					<a-spin tip="正在搜索..." />
				</div>
			</div>
		</div>
	</a-modal>
</template>

<script>
import axios from 'axios';

export default {
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		keyWord: {
			type: String,
			default: ''
		},
		fieldName: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			searchKeyword: this.keyWord || '', // 本地搜索关键词
			results: [],
			loading: false,
			// tk: '57da9c5fd91e43b6ddad1a13ddef1bba',
			key: 'b22adbd041f6691dae2394f44d93235b',
		};
	},
	watch: {
		// 监听父组件传入的keyWord变化
		keyWord(newVal) {
			this.searchKeyword = newVal || '';
			// 当父组件传递的关键词变化时，自动触发搜索
			if (newVal) {
				this.handleSearch();
			}
		},
		visible(newVal) {
			// 当弹窗显示时，自动聚焦搜索框
			if (newVal) {
				this.searchKeyword = this.keyWord || '';
				this.$nextTick(() => {
					const input = this.$refs.searchInput;
					if (input) {
						input.focus();
					}
				});
			} else {
				// 弹窗关闭时清空结果
				this.results = [];
			}
		}
	},
	methods: {
		// 处理搜索事件
		async handleSearch() {
			if (!this.searchKeyword.trim()) {
				this.results = [];
				return;
			}

			this.loading = true;
			try {
				// const params = {
				// 	keyWord: this.searchKeyword,
				// 	level: 12,
				// 	mapBound: "73.6,3.86,135.05,53.55", // 全中国范围
				// 	queryType: 1,
				// 	start: 0,
				// 	count: 10
				// };
				// const proxyUrl = `http://api.tianditu.gov.cn/v2/search?postStr=${encodeURIComponent(JSON.stringify(params))}&type=query&tk=${this.tk}`;
				const proxyUrl = `https://restapi.amap.com/v5/place/text?key=${this.key}&keywords=${this.searchKeyword}`;
				const response = await axios.get(proxyUrl);
				console.log('搜索结果:', response.data);
				// 根据天地图API实际返回结构处理数据
				// if (response.data && response.data.status && response.data.status.infocode === 1000) {
				// 	this.results = response.data.pois || [];
				// 	if (this.results.length === 0) {
				// 		this.$message.info('未找到相关地点，请尝试其他关键词');
				// 	}
				// } else {
				// 	this.$message.error('搜索失败，请重试');
				// 	this.results = [];
				// }
				if (response.data && response.data.status && response.data.infocode == 10000) {
					this.results = response.data.pois || [];
					if (this.results.length === 0) {
						this.$message.info('未找到相关地点，请尝试其他关键词');
					}
				} else {
					this.$message.error('搜索失败，请重试');
					this.results = [];
				}
			} catch (error) {
				console.error('搜索错误:', error);
				this.$message.error('网络异常，请检查连接');
				this.results = [];
			} finally {
				this.loading = false;
			}
		},
		// 选择地点
		selectLocation(item) {
			this.$emit('select', {
				name: item.name,
				// lonlat: item.lonlat,
				location: item.location,
				address: item.address,
				fieldName: this.fieldName
			}); // 触发父组件事件
			this.handleClose();
		},
		// 关闭弹窗
		handleClose() {
			this.$emit('close');
		}
	}
};
</script>

<style scoped>
.search-container {
	padding: 0;
}

.results-container {
	margin-top: 16px;
	max-height: 400px;
	overflow-y: auto;
}

.location-name {
	color: #1890ff;
	cursor: pointer;
	font-weight: 500;
}

.location-name:hover {
	color: #40a9ff;
}

.location-address {
	color: #666;
	font-size: 13px;
	margin-top: 4px;
}

.loading-container {
	text-align: center;
	padding: 20px;
}

:deep(.ant-list-item) {
	padding: 12px 0;
	border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-list-item:last-child) {
	border-bottom: none;
}

:deep(.ant-modal-body) {
	padding: 24px;
}
</style>